﻿using fmtx.Framework.DALFactory;
using fmtx.Framework.DESC;
using fmtx.Framework.Web;
using SYH.Domain.Applicaton;
using SYH.Domain.ViewModels.Applicaton;
using SYH.IWebBLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SYH.Web.Models
{
    public class LoginService
    {
        private const string SESSIONUSER = "LogonSystemUser";
        private const string COOKIETOKEN = "syh-user-cook-id";
        private const string COOKIEENCRYKEY = "zxcvbnma";
        private const string SESSIONTOKEN = "SYH-Logon-TOKEN";

        /// <summary>
        /// 返回当前用户登录信息
        /// </summary>
        public static LoginUserVM LogUser
        {
            get
            {
                LoginUserVM res = null;
                object user = System.Web.HttpContext.Current.Session[SESSIONUSER];
                if (user == null)
                {
                    var id = WebCookieHelper.GetCookie(COOKIETOKEN, COOKIEENCRYKEY);
                    if (!string.IsNullOrEmpty(id))
                    {
                        System.Web.HttpContext.Current.Session[SESSIONTOKEN] = id;
                        var db = FactoryService.GetObject<ISession>();
                        var bo = db.Get(Guid.Parse(id));
                        System.Web.HttpContext.Current.Session[SESSIONUSER] = bo;
                        res = bo;
                    }
                }
                else
                {
                    res = user as LoginUserVM;
                }
                return res;
            }
        }

        /// <summary>
        /// 设置登录
        /// </summary>
        /// <param name="suser"></param>
        /// <returns></returns>
        public static LoginUserVM SetLogin(SystemUser suser)
        {
            var user = new LoginUserVM(suser);
            System.Web.HttpContext.Current.Session[SESSIONUSER] = user;
            var db = FactoryService.GetObject<ISession>();
            var token = db.LogToken(user).ToString();
            System.Web.HttpContext.Current.Session[SESSIONTOKEN] = token;
            WebCookieHelper.SetCookie(COOKIETOKEN, COOKIEENCRYKEY, token);
            System.Web.HttpContext.Current.Response.Cookies.Add(new HttpCookie("name", DESCHandler.MD5_32(DateTime.Now.ToString())));
            return user;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void SetOut()
        {
            var token = WebCookieHelper.GetCookie(COOKIETOKEN, COOKIEENCRYKEY);
            var db = FactoryService.GetObject<ISession>();
            db.Remove(Guid.Parse(token));
            WebCookieHelper.RemoveCookie();
            System.Web.HttpContext.Current.Session.Clear();
        }
    }
}